package cool.taomu.toolkit.freemarker

import cool.taomu.toolkit.template.ITemplate
import freemarker.template.Configuration
import java.io.File
import java.io.StringWriter
import java.util.Map
import org.apache.commons.lang3.exception.ExceptionUtils
import org.slf4j.LoggerFactory

class FreemarketUtils implements ITemplate{
	val static LOG = LoggerFactory.getLogger(FreemarketUtils);

	override execute(String path, Map<String, Object> dataModel) {
		var subPath = path.substring(0, path.lastIndexOf(File.separator) + 1);
		var template = path.substring(path.lastIndexOf(File.separator) + 1);
		return freemarker(subPath, template, dataModel);
	}

	def freemarker(String basePath, String template, Map<String, Object> dataModel) {

		var StringWriter writer = new StringWriter();
		try {
			var Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
			cfg.directoryForTemplateLoading = new File(basePath);
			cfg.getTemplate(template).process(dataModel, writer);
		} catch (Exception ex) {
			writer.flush();
			LOG.info(ExceptionUtils.getStackTrace(ex));
			writer.append(ExceptionUtils.getStackTrace(ex))
		}
		return writer
	}
}
